package com.jiang.annotation.valid.test;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.jiang.annotation.valid.custom.EnumValueCheck;
import com.jiang.annotation.valid.custom.InValuesCheck;
import com.jiang.annotation.valid.custom.enum1.IntegerTypeEnum;
import com.jiang.annotation.valid.custom.enum1.StringTypeEnum;

import com.jiang.annotation.valid.group.Group1;
import com.jiang.annotation.valid.group.Group2;
import lombok.Data;
import lombok.experimental.Accessors;
import org.hibernate.validator.constraints.ScriptAssert;
import org.springframework.format.annotation.DateTimeFormat;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;

@Data
@Accessors(chain = true)
@ScriptAssert(script = "com.jiang.annotation.valid.test.User.checkName(_this.name)", lang = "javascript", message = "{script}，用户名不能为空且不能包含! @ # $ % & * \\ / ? ？特殊符号")
public class User implements Serializable {

    private static final long serialVersionUID = -5377638533206539277L;

    private Long userId;

    @Size(min = 2, max = 10)
    private String name;

    @NotNull
//    @InValuesCheck(strValues = {"男", "女"}, canNull = false, message = "value must be in {strValues}")
    @EnumValueCheck(enumClass = StringTypeEnum.class)
    private String sex;

    @EnumValueCheck(enumClass = IntegerTypeEnum.class, groups = {Group1.class, Group2.class})
    private int grade;

    @InValuesCheck(intValues = {20, 21, 22, 23, 24}, groups = {Group2.class}, canNull = false, message = "value must be in {intValues}")
    private int graduateAge;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    private String address;


    /**
     * 检查用户名是否包含特殊字符
     *
     * @param name
     * @return
     */
    public static boolean checkName(String name) {
        if (Objects.isNull(name)) {
            return Boolean.FALSE;
        }

        if (name.length() > 4) {
            return Boolean.FALSE;
        }

        String[] chars = {"!", "@", "#", "$", "%", "&", "*", "\\", "/", "?", "？"};
        for (String c : chars) {
            if (name.contains(c)) {
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }
}